#include "TreeDirectoryWidget.h"
#include "ui_TreeDirectoryWidget.h"
#include <QScrollArea>
#include <QMessageBox>
#include <qheaderview.h>
// #include "Language.h"
#define status_index 24
#define ParentTreeID 25
#define NoneParent 9999

TreeDirectoryWidget::TreeDirectoryWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TreeDirectoryWidget)
{
    ui->setupUi(this);
	QScreen* screen = QGuiApplication::primaryScreen();
	QRect screenSize = screen->availableGeometry();
	int screenWidth = screenSize.width();
	int screenHight = screenSize.height();
	_widthScale = (double)screenWidth / 1920.0;
	_hightScale = (double)screenHight / 1080.0;

	_menu = new QMenu(_leftTree);
	_menu->addAction("通道详情");

	connect(_menu, &QMenu::triggered, this, &TreeDirectoryWidget::menuAction);

	initTree();
	connect(_leftTree, SIGNAL(itemPressed(QTreeWidgetItem*, int)), this, SLOT(tree_itemPressed(QTreeWidgetItem*, int)));
	connect(_leftTree, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(tree_itemDoubleClicked(QModelIndex)));
	connect(_leftTree, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this, SLOT(tree_itemChanged(QTreeWidgetItem*, int)));
	connect(ui->pushButton, SIGNAL(clicked(bool)), this, SLOT(btn_expandingTreeNode(bool)));
	//connect(ui->lineEdit,&QLineEdit::returnPressed,this,SLOT(search));
}

TreeDirectoryWidget::~TreeDirectoryWidget()
{
	if (_menu)
	{
		_menu->clear();
		delete _menu;
		_menu = nullptr;
	}
    delete ui;
}

void TreeDirectoryWidget::expandParentTreeItem(QTreeWidgetItem* item)
{
	if (item->data(0, Qt::UserRole + ParentTreeID).toString() == QString::number(NoneParent))
		return;
	else
	{
		QString pid = item->data(0, Qt::UserRole + ParentTreeID).toString();
		if (_treeItemMap.contains(pid))
		{
			auto pItem = _treeItemMap.value(pid);
			pItem->setHidden(false);
			pItem->setExpanded(true);
			expandParentTreeItem(pItem);
		}
	}
}

void TreeDirectoryWidget::search()
{
	QString text = ui->lineEdit->text();
	if (text.isEmpty() || text.isNull())
	{
		for (auto item : _treeItemMap.values())
		{
			item->setHidden(false);
			item->setExpanded(false);   //是否展开每一项
		}
		scroll->hide();
		return;
	}
	else
	{
		for (QString countryNmae : _treeItemMap.keys())
		{
			if (countryNmae.contains(text))
			{
				auto rootItem = _treeItemMap.value(countryNmae);
				if (rootItem)
				{
					rootItem->setHidden(false);
					scroll->show();
				}
			}
			else
			{
				_treeItemMap.value(countryNmae)->setHidden(true);
				scroll->hide();
			}
		}
		for (QString leafname : _treeNameMap.keys())
		{
			if (leafname.contains(text))
			{
				auto leafItem = _treeNameMap.value(leafname);
				auto _parent = dynamic_cast<QTreeWidgetItem*>(leafItem->parent());
				for (auto item : _treeItemMap.values())
				{
					if (item == _parent)
					{
						item->setHidden(false);
						item->setExpanded(true);
					}
				}
				leafItem->setHidden(false);
				scroll->show();
			}
			else
			{
				_treeNameMap.value(leafname)->setHidden(true);
				scroll->hide();
			}
		}
	}
}

void TreeDirectoryWidget::showWaiting()
{
	//转圈

	scroll->hide();
	_leftTree->hide();
}

void TreeDirectoryWidget::hideWaiting()
{
	scroll->show();
	_leftTree->show();
}


void TreeDirectoryWidget::btn_expandingTreeNode(bool check)
{
	search();
}

void TreeDirectoryWidget::keyPressEvent(QKeyEvent* event)
{
	//回车键进入时间，两个Enter,两种类型
	qDebug() << "event-type" << event->key();
	switch (event->key())
	{
	case Qt::Key_Return:
		btn_expandingTreeNode(true);
		break;
	case Qt::Key_Enter:
		btn_expandingTreeNode(true);
		break;
	default:
		break;
	}
}

void TreeDirectoryWidget::selectAndshowTreeNode(int index)
{
	//QMessageBox::about(nullptr,"index",QString::number(index));
	if (index == 99)
	{
		for (auto item : _treeItemMap.values())
		{
			item->setHidden(false);
			item->setExpanded(false);   //是否展开每一项
		}
	}
	else
	{
		for (auto item : _treeItemMap.values())
		{
			item->setHidden(true);
		}
		for (auto item : _treeItemMap.values())
		{
			if (item->data(0, Qt::UserRole + status_index).toInt() == index)
			{
				expandParentTreeItem(item);
				item->setHidden(false);
			}
		}
	}
}


void TreeDirectoryWidget::initTree()
{
	if (scroll == NULL)
		scroll = new QScrollArea(ui->widget);
	scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
	scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
	scroll->resize(ui->widget->width(), ui->widget->height());
	scroll->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
	if (_leftTree == NULL)
		_leftTree = new QTreeWidget(scroll);
	_leftTree->header()->hide();
	QHBoxLayout* layout = new QHBoxLayout();
	layout->setContentsMargins(0, 0, 0, 0);
	layout->addWidget(_leftTree);
	ui->widget->setLayout(layout);
	_leftTree->setGeometry(0, 0, scroll->width(), scroll->height());
}

QString TreeDirectoryWidget::CreateRootLeafNode(QString name, QString pid)
{
	if (pid == NULL)  //创建根节点
	{
		if (_leftTree == NULL)
			initTree();
		rootTreeItem = new QTreeWidgetItem(_leftTree);
		rootTreeItem->setText(0, name);  //0或1
		rootTreeItem->setCheckState(0, Qt::Unchecked);
		//_leftTree->addTopLevelItem(rootTreeItem);
		//_leftTree->expandItem(rootTreeItem);    //展开节点
		QString rootId = QString::number(index++) + name;
		_treeItemMap.insert(rootId, rootTreeItem);
		rootTreeItem->setData(0, Qt::UserRole + 5, rootId);  
		rootTreeItem->setData(0, Qt::UserRole + 6, name);  
		rootTreeItem->setData(0, Qt::UserRole + ParentTreeID, NoneParent);
		rootTreeItem->setData(0, Qt::UserRole + status_index, 99);
		return rootId;
	}
	else    //创建叶子结点
	{
		if (_treeItemMap.contains(pid))
		{
			auto item = _treeItemMap.value(pid);
			rootTreeItem = new QTreeWidgetItem(item);
			rootTreeItem->setCheckState(0, Qt::Unchecked);
			rootTreeItem->setText(0, name);
			QString rootId = QString::number(index++) + name;
			_treeItemMap.insert(rootId, rootTreeItem);
			_treeNameMap.insert(name, rootTreeItem);
			rootTreeItem->setData(0, Qt::UserRole + 5, rootId);   
			rootTreeItem->setData(0, Qt::UserRole + 6, name);   
			rootTreeItem->setData(0, Qt::UserRole + ParentTreeID, pid);
			rootTreeItem->setData(0, Qt::UserRole + status_index, 99);
			return rootId;
		}
		else
			return NULL;
	}
}

bool TreeDirectoryWidget::CreateChildLeafNode(treeItemInfo* info, QString pid)
{
	if (info == NULL)
		return false;
	if (pid != NULL) //存在创建子节点
	{
		if (_treeItemMap.contains(pid))
		{
			auto item = _treeItemMap.value(pid);    //获取父节点
			LeafTreeItem = new QTreeWidgetItem(item);
			LeafTreeItem->setText(0, info->GetTreeItemName());
			LeafTreeItem->setTextColor(0, info->GetStatusColor());
			int count = item->childCount();
			QString txt = item->data(0, Qt::UserRole + 6).toString();
			item->setText(0, txt + "(" + QString::number(count) + ")");

			_treeItemMap.insert(info->GetTreeItemID(), LeafTreeItem);
			_treeNameMap.insert(info->GetTreeItemName(), LeafTreeItem);
			//leaftreeitem->setMenu(_menu);

			LeafTreeItem->setData(0, Qt::UserRole + 5, info->GetTreeItemID());   
			LeafTreeItem->setData(0, Qt::UserRole + 6, info->GetTreeItemName());   
			LeafTreeItem->setData(0, Qt::UserRole + 9, info->GetDoubleClickCode());
			LeafTreeItem->setData(0, Qt::UserRole + 10, info->GetCheckChangeCode());
			LeafTreeItem->setData(0, Qt::UserRole + ParentTreeID, pid);
			LeafTreeItem->setData(0, Qt::UserRole + status_index, info->statusIndex);
			//            if(info->GetCheckAble())
			//            {
			//                LeafTreeItem->setCheckState(0,info->checkstate);
			//            }
			//            else
			LeafTreeItem->setCheckState(0, Qt::Unchecked);
			return true;
		}
		else
			return false;
	}
	else
	{
		LeafTreeItem = new QTreeWidgetItem(_leftTree);
		LeafTreeItem->setText(0, info->GetTreeItemName());
		_treeItemMap.insert(info->GetTreeItemID(), LeafTreeItem);

		LeafTreeItem->setData(0, Qt::UserRole + 5, info->GetTreeItemID());   //存在通用变量中
		LeafTreeItem->setData(0, Qt::UserRole + 6, info->GetTreeItemName());
		LeafTreeItem->setData(0, Qt::UserRole + 9, info->GetDoubleClickCode());
		LeafTreeItem->setData(0, Qt::UserRole + 10, info->GetCheckChangeCode());
		LeafTreeItem->setData(0, Qt::UserRole + ParentTreeID, NoneParent);
		LeafTreeItem->setData(0, Qt::UserRole + status_index, info->statusIndex);

		_leftTree->addTopLevelItem(LeafTreeItem);
		//        if(info->GetCheckAble())
		//        {
		//            LeafTreeItem->setCheckState(0,info->checkstate);
		//        }
		//        else
		LeafTreeItem->setCheckState(0, Qt::Unchecked);
		return true;
	}
}

bool TreeDirectoryWidget::UpdateChildLeafNode(treeItemInfo* info)
{
	if (info)
	{
		QString name = info->GetTreeItemName();
		QString id = info->GetTreeItemID();
		if (_treeItemMap.contains(id))
		{
			auto item = _treeItemMap.value(id);
			item->setText(0, name);
			item->setTextColor(0, info->GetStatusColor());
		}
		else
		{
			//不存在创建叶子节点
			CreateChildLeafNode(info, id);
		}
		return true;
	}
	else
		return false;
}

void TreeDirectoryWidget::setLeafNodeCheck(QString id, bool state)
{
	if (_treeItemMap.contains(id))
	{
		auto item = _treeItemMap.value(id);
		if (item)
		{
			Qt::CheckState sate = state ? Qt::Checked : Qt::Unchecked;
			if (item->checkState(0) != sate)
				item->setCheckState(0, sate);
		}
	}
}

void TreeDirectoryWidget::clearTreeNode(QString id)
{
	if (_treeItemMap.contains(id))
	{
		auto item = _treeItemMap.value(id);
		if (item)
		{
			if (item->childCount() > 0)
			{
				for (auto chileItem : item->takeChildren())
				{
					QString cid = chileItem->data(0, Qt::UserRole + 5).toString();
					clearTreeNode(cid);
				}
			}
			item->setHidden(true);
			delete item;
		}
	}
}

void TreeDirectoryWidget::clearAllNode()
{
	for (auto item : _treeItemMap.values())
	{
		item->setHidden(true);
		_leftTree->removeItemWidget(item, 0);
	}
	_treeItemMap.clear();
}

void TreeDirectoryWidget::menuAction(QAction* action)
{
	if (_menu == nullptr)
		return;
	if (action->text() == ("通道详情"))
	{
		if (_leftTree)
		{
			QList<QTreeWidgetItem*> selects = _leftTree->selectedItems();
			if (selects.count() > 0)
			{
				QString str = selects.at(0)->data(0, Qt::UserRole + 9).toString();
				qDebug() << "checkbox selected right key: " << str;
				emit sig_itemMenuClick(str);
			}
		}
	}
}

void TreeDirectoryWidget::tree_itemChanged(QTreeWidgetItem* item, int column)
{
	//获取节点勾选状态时要发送的信息

	if (item)
	{

		for (int i = 0; i < item->childCount(); i++)
		{
			item->child(i)->setCheckState(0, item->checkState(0));
		}
		bool check = item->checkState(0) == Qt::Checked ? true : false;
		QString str = item->data(0, Qt::UserRole + 5).toString();
		QString id = item->data(0, Qt::UserRole + 10).toString();    //QVariant 通用类型
		if (id.isEmpty())
			return;
		emit sig_itemCheckChange(id, check);
		qDebug() << " checkbox item change: " << str << "  id=" << id << " check=" << check;
	}
}

void TreeDirectoryWidget::tree_itemDoubleClicked(const QModelIndex& index)
{
	if (_leftTree)
	{
		QList<QTreeWidgetItem*> selects = _leftTree->selectedItems();
		if (selects.count() > 0)
		{
			QString str = selects.at(0)->data(0, Qt::UserRole + 9).toString();
			qDebug() << "checkbox double click：" << str;
			emit sig_itemDoubliClicked(str);
		}

	}
}

void TreeDirectoryWidget::tree_itemPressed(QTreeWidgetItem* item, int column)
{
	if (qApp->mouseButtons() == Qt::RightButton)
	{
		if (_menu)
			_leftTree->addActions(_menu->actions());
		_leftTree->setContextMenuPolicy(Qt::ActionsContextMenu);
	}
}

/**********************************
 * 函数名：TreeDirectoryWidget::initTreeData
 * 功能：初始化树的节点信息
 * 输入：无
 * 输出：无
 * 备注：无
**********************************/
void TreeDirectoryWidget::initTreeData(QMap<int, DevStationData* >& devMap)
{
	for (int i = 1; i <= 100; i++)
	{
		DevStationData* data = new DevStationData();
		if (i <=20)
		{
			data->setType( ("通道1-20"));
			data->setDevName( ("通道") + QString::number(i));
		}
		else if (20<i && i<=40)
		{
			data->setType( ("通道20-40"));
			data->setDevName( ("通道") + QString::number(i));
		}
		else if (40 < i && i <= 60)
		{
			data->setType( ("通道40-60"));
			data->setDevName( ("通道") + QString::number(i));
		}
		else if (60 < i && i <= 80)
		{
			data->setType( ("通道60-80"));
			data->setDevName( ("通道") + QString::number(i));
		}
		else if (80 < i && i <= 100)
		{
			data->setType( ("通道80-100"));
			data->setDevName( ("通道") + QString::number(i));
		}
		//data->setStatus(DevStatus(status));
		data->setDevCode(QString::number(i));
		devMap.insert(i, data);
	}
	QMap<QString, QString> treeIdmap;    //type和id

	if (this)
	{
		for (auto& pair : devMap.toStdMap())
		{
			auto channel = pair.first;
			auto data = pair.second;
			QString code = data->getDevCode();
			QString type = data->getType();
			if (treeIdmap.contains(type))
			{
				QString Treeid = treeIdmap.value(type);
				this->CreateChildLeafNode((treeItemInfo*)data, Treeid);
				//_treeWidget->setLeafNodeCheck(code,true);
			}
			else
			{
				QString treeId = this->CreateRootLeafNode(type);
				this->CreateChildLeafNode((treeItemInfo*)data, treeId);
				treeIdmap.insert(type, treeId);
			}
		}
	}
}


